<?php

/**
 * 项目动态、通知公告 控制器
 * @author YangL
 * */

namespace Admin\Controller;

use Common\Controller\WahahabaseController;

class NewsController extends WahahabaseController {

    public function _initialize() {
        parent::_initialize();
        $this->deal_model = D("Common/News");
        $this->att_model = D("Common/Attachment");
    }

    //主页方法
    public function indexPage($where) {
        $eq = array(
            "eq" => "=",
            "neq" => "!=",
            "gt" => ">",
            "egt" => ">=",
            "lt" => "<",
            "elt" => "<=",
            "like" => "LIKE"
        );
        // 当前登录人
        $adminId = session('ADMIN_ID');

        $condition = "(
            (d.is_publish = 0 AND (d.add_user = $adminId OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department) AND ((SELECT role_id FROM hzzy_users WHERE id=$adminId) IN('2','3'))))
            OR
            (d.is_publish = 1)
        )";
        foreach ($where as $key => $v) {
            if (count($v) > 1) {
                $d = $eq[$v[0]] == NULL ? '=' : $eq[$v[0]];
                if ($d != 'LIKE') {
                    $condition .= " AND $key $d '" . $v[1] . "'";
                } else {
                    $condition .= " AND $key $d '%" . $v[1] . "%'";
                }
            } else {
                $condition .= " AND $key = '$v'";
            }
        }
        $count = $this->deal_model->alias("d")->where($condition)->count();
        $page = $this->page($count, 20);

        $results = $this->deal_model->alias("d")
                ->field('d.*,u.real_name')
                ->join(array(
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON d.add_user = u.id',
                ))
                ->where($condition)
                ->order("d.add_time DESC")
                ->limit($page->firstRow, $page->listRows)
                ->select();
        //exit($this->deal_model->getLastSql());
        $this->getDepartLevel();
        $this->assign("page", $page->show('Admin'));
        $this->assign("results", $results);

        $this->display();
    }

    // 项目动态
    public function index() {

        $where = array('type' => array('eq', 1),
            "d.is_deleted" => array('eq', 0));
        $title = trim(I('request.title'));
        if ($title) {
            $where['title'] = array('like', "%$title%");
        }
        $this->indexPage($where);
    }

    public function add() {
        $this->display();
    }

    public function add_post() {
        if (IS_POST) {
            // 合并底层数据
            $data = array_merge($_POST, $this->saveData());
            $data['publish_time'] = date('Y-m-d H:i:s', time());
            $data['author'] = session('ADMIN_ID');
            if ($this->deal_model->create() !== false) {
                $result = $this->deal_model->add($data);
                if ($result !== false) {
                    $this->success("添加成功！", U("News/index"));
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }

    public function view() {
        $id = I('get.id', 0, 'intval');
        $res = $this->deal_model->alias("d")
                ->field('d.*,u.real_name')
                ->join(array(
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON d.add_user = u.id',
                ))
                ->where("d.id = $id")
                ->select();
        $this->assign("results", $res);
        $this->getinfo();
    }

    public function edit() {
        $this->getinfo();
    }

    private function getinfo() {
        $id = I('get.id', 0, 'intval');
        $where = array(
            'id' => array('eq', $id)
        );

        $news = $this->deal_model->field("id,title,content,source,author,publish_time,thumbnail,hits_count,is_publish")->where($where)->find();
        //访问量加1
        $news['hits_count'] = $news['hits_count'] + 1;
        $this->deal_model->save($news);
        $this->assign("news", $news);
        $this->display();
    }

    public function edit_post() {
        if (IS_POST) {
            $data = array_merge($_POST, $this->saveData(2));
            if ($this->deal_model->create() !== false) {
                $result = $this->deal_model->save($data);
                if ($result !== false) {
                    $this->success("保存成功！", U("News/index"));
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }

    // 上传缩略图
    public function uploadImg() {
        if (is_uploaded_file($_FILES['upFile']['tmp_name'])) {
            // 验证图片宽高信息
            $uploadSize = getimagesize($_FILES['upFile']['tmp_name']);
//			$width = $uploadSize[0];
//			$height = $uploadSize[1];
//			if($width != $height || $width != 200){
//				// 输出结果
//				exit(json_encode(array(
//					'rtnType'	=> 'F',
//					'rtnMsg'	=> "您上传的图片比例不符合要求！",
//					'rtnResult'	=> ''
//				)));
//			}
            $upfile = $_FILES["upFile"];
            //获取数组里面的值 
            $name = $upfile["name"]; //上传文件的文件名 
            $type = $upfile["type"]; //上传文件的类型 
            //$size = $upfile["size"];//上传文件的大小 
            $tmp_name = $upfile["tmp_name"]; //上传文件的临时存放路径 
            //判断是否为图片 
            switch ($type) {
                case 'image/pjpeg':
                    $okType = true;
                    break;
                case 'image/jpeg':
                    $okType = true;
                    break;
                case 'image/gif':
                    $okType = true;
                    break;
                case 'image/png':
                    $okType = true;
                    break;
            }

            // 上传结果
            $rtnType = "F";
            $destination = "";
            if ($okType) {
                /**
                 * 0:文件上传成功<br/> 
                 * 1：超过了文件大小，在php.ini文件中设置<br/> 
                 * 2：超过了文件的大小MAX_FILE_SIZE选项指定的值<br/> 
                 * 3：文件只有部分被上传<br/> 
                 * 4：没有文件被上传<br/> 
                 * 5：上传文件大小为0 
                 */
                $error = $upFile["error"]; //上传后系统返回的值 
//				echo "================<br/>"; 
//				echo "上传文件名称是：".$name."<br/>"; 
//				echo "上传文件类型是：".$type."<br/>"; 
//				echo "上传文件大小是：".$size."<br/>"; 
//				echo "上传后系统返回的值是：".$error."<br/>"; 
//				echo "上传文件的临时存放路径是：".$tmp_name."<br/>"; 
//				
//				echo "开始移动上传文件<br/>";
//				$path = "/usr/www/html/index.php";
//				$pathinfo = pathinfo($path);
//				echo "目录名称：$pathinfo[dirname]<br>";
//				echo "文件名称：$pathinfo[basename]<br>";
//				echo "扩展名：$pathinfo[extension]";
//				运行结果：
//				目录名称：/usr/www/html
//				文件名称：index.php
//				扩展名：php
                // 获取文件后缀
                $pathinfo = pathinfo($name);

                $destination = "data/upload/news/" . date('Ymd');
                if (!file_exists($destination)) {
                    mkdir("$destination", 0777, true);
                }
                $destination .= "/" . time() . '.' . $pathinfo['extension'];
                // 如果有原始图片地址信息，删除图片
                if (file_exists($_POST['imageURL'])) {
                    unlink($_POST['imageURL']);
                }

                //把上传的临时文件移动到up目录下面 
                move_uploaded_file($tmp_name, $destination);

//				echo "================<br/>"; 
//				echo "上传信息：<br/>"; 
                if ($error == 0) {
                    $rtnType = "T";
                    $rtnMsg = "文件上传成功啦！";

//					echo "文件上传成功啦！"; 
//					echo "<br>图片预览:<br>"; 
//					echo "<img src=".$destination.">"; 
//					echo " alt=\"图片预览:\r文件名:".$destination."\r上传时间:\">"; 
                } elseif ($error == 1) {
                    $rtnMsg = "超过了文件大小，在php.ini文件中设置";
                } elseif ($error == 2) {
                    $rtnMsg = "超过了文件的大小MAX_FILE_SIZE选项指定的值";
                } elseif ($error == 3) {
                    $rtnMsg = "文件只有部分被上传";
                } elseif ($error == 4) {
                    $rtnMsg = "没有文件被上传";
                } else {
                    $rtnMsg = "上传文件大小为0";
                }
            } else {
                $rtnMsg = "请上传jpg,gif,png等格式的图片！";
            }

            // 输出结果
            exit(json_encode(array(
                'rtnType' => $rtnType,
                'rtnMsg' => $rtnMsg,
                'rtnResult' => $destination
            )));
        }
    }

    // 通知公告
    public function notice() {
        $where = array('type' => array('eq', 2),
            "d.is_deleted" => array('eq', 0));
        $title = trim(I('request.title'));
        if ($title) {
            $where['title'] = array('like', "%$title%");
        }
        $this->getDepartLevel();
        $this->indexPage($where);
    }

    // 添加公告
    public function addnotice() {
        $this->display();
    }

    public function addFilePost($url, $type) {
        if (IS_POST) {
            $this->dataCheck();
            $data = array_merge($_POST, $this->saveData());
            $data['publish_time'] = date('Y-m-d H:i:s', time());
            if ($this->deal_model->create() !== false) {
                $result = $this->deal_model->add($data);
                if ($result !== false) {
                    $this->saveFile($result, $type);
                    $this->success("添加成功！", $url);
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }

    public function addnotice_post() {
        $this->addFilePost(U("News/notice"), 7);
    }

    // 修改公告
    public function editnotice() {
        $id = I('get.id', 0, 'intval');
        $where = array(
            'id' => array('eq', $id)
        );
        $news = $this->deal_model->field("id,title,content,source,author,publish_time")->where($where)->find();
        $this->assign("news", $news);

        $results = $this->att_model->where(array("table_id" => $id, "belong_to" => 7))->select();
        $this->assign("results", $results);

        $this->display();
    }

    public function editnotice_post() {
        $this->editFilePost(U("News/notice"), 7);
    }

    public function noticeview() {
        $id = I('get.id', 0, 'intval');
        $where = array(
            'id' => array('eq', $id)
        );
        $news = $this->deal_model->field("id,title,content,source,author,publish_time,hits_count,is_publish")->where($where)->find();
        //访问量+1
        $news['hits_count'] = $news['hits_count'] + 1;
        $this->deal_model->save($news);
        $this->assign("news", $news);

        $results = $this->att_model->where(array("table_id" => $id, "belong_to" => 7))->select();
        $this->assign("results", $results);

        $this->display();
    }

    #####接口123####

    public function getNewsByAjax() {
        $info = $this->deal_model
                ->field('id,title,thumbnail,content')
                ->where(array('type' => 1, 'is_publish' => 1, 'is_deleted' => 0, 'thumbnail' => array('neq', '')))
                ->order("add_time DESC")
                ->limit(5)
                ->select();
        exit(json_encode(
                        array(
                            'rtnType' => 'T',
                            'rtnData' => $info
                        )
        ));
    }

    public function getNoticeByAjax() {
        $info = $this->deal_model
                ->field('id,title,thumbnail,content')
                ->where(array('type' => 2, 'is_publish' => 1, 'is_deleted' => 0))
                ->order("add_time DESC")
                ->limit(7)
                ->select();
        exit(json_encode(
                        array(
                            'rtnType' => 'T',
                            'rtnData' => $info
                        )
        ));
    }

    ##################接口##########################
}
